import { formatToDateTime } from '@/utils/dateUtil';

export function useTableAction() {
  /**
   * 处理查询参数的时间字段
   * @param arg 查询参数
   * @param keyword 时间字段关键字
   */
  const handleFetchDateParams = (arg: any, keyword: string = 'Time') => {
    const keys = Object.keys(arg);
    keys?.forEach?.((key) => {
      if (key.includes(keyword)) {
        const val = arg[key];
        if (val?.length) {
          arg[`${key}From`] = formatToDateTime(val[0], 'YYYY-MM-DD 00:00:00.SSS');
          arg[`${key}To`] = formatToDateTime(val[1], 'YYYY-MM-DD 23:59:59.SSS');
          delete arg[key];
        }
      }
    });
  };

  /**
   * 获取操作列配置
   * @param width 列宽度
   * @param moreConfig 更多的列配置
   */
  const getActionColumn = (width: number | string = 200, moreConfig?: any) => {
    return {
      width,
      title: '操作',
      fixed: 'right',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      ...(moreConfig || {}),
    };
  };

  /**
   * 从某数据源内
   * @param list 数据源
   * @param val key值
   * @param key 检索的key
   */
  const findLabel = (list: Array<any>, val: any, key: string = 'key') => {
    return list?.find?.((find) => find?.[key] === val)?.label || '';
  };

  return {
    findLabel,
    getActionColumn,
    handleFetchDateParams,
  };
}
